package com.clwl.supervise.superviseapp.controller.inspection;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.clwl.supervise.superviseapp.config.RepeatSubmit;
import com.clwl.supervise.superviseapp.entity.base.CommonSearchEntity;
import com.clwl.supervise.superviseapp.entity.base.rectificationSituationData.RectificationSituationData;
import com.clwl.supervise.superviseapp.entity.result.ResultEntity;
import com.clwl.supervise.superviseapp.entity.risk.JgPointDistance;
import com.clwl.supervise.superviseapp.entity.supervise.JgDailyCheck;
import com.clwl.supervise.superviseapp.service.base.BaseDataService;
import com.clwl.supervise.superviseapp.service.inspect.DailyInspectService;
import com.clwl.supervise.superviseapp.service.inspect.DoubleRandomCheckService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 双随机检查
 */
@RestController
@RequestMapping("/doubleRandomCheck")
@Slf4j
public class DoubleRandomCheckController {

    @Resource
    private DoubleRandomCheckService doubleRandomCheckService;

    @Resource
    private BaseDataService baseDataService;


    @Resource
    private DailyInspectService dailyInspectService;


    /**
     * 获取双随机检查的企业列表
     * @param pageNum 当前页数
     * @param pageSize 每页数据数量
     * @return
     */
    @GetMapping("page")
    public ResultEntity<List<Map<String,Object>>> page(Integer pageNum, Integer pageSize, CommonSearchEntity commonSearchEntity) {
        IPage<Map<String,Object>> pageList = doubleRandomCheckService.selectDoubleRandomCheckPage(pageNum,pageSize,commonSearchEntity);
        return ResultEntity.success(pageList.getRecords());
    }




    /**
     *  检查结果列表
     * @param pageNum 当前页数
     * @param pageSize 每页数据数量
     * @return
     */
    @GetMapping("inspectionResultPage")
    public ResultEntity<List<Map<String,Object>>> inspectionResultPage(Integer pageNum, Integer pageSize, CommonSearchEntity commonSearchEntity
    ) {
        IPage<Map<String,Object>> pageList = doubleRandomCheckService.selectInspectionResultPage(pageNum,pageSize,commonSearchEntity);
        return ResultEntity.success(pageList.getRecords());
    }


    /**
     * 获取检查的时候基础信息
     * @param companyId 企业id
     * @return
     */
    @GetMapping("getInspectionBaseInfo")
    @RepeatSubmit
    public ResultEntity<Map<String,Object>> getInspectionBaseInfo(Long companyId){
        try {
            if( companyId == null){
                return ResultEntity.error("请传递企业id");
            }
            //Map<String,Object> superviseInfo = doubleRandomCheckService.selectSuperviseInfo(companyId);
            Map<String,Object> checkInfo =  doubleRandomCheckService.selectCheckInfo(companyId);
            JgPointDistance distance =  baseDataService.getCheckDistance(companyId+"");
            checkInfo.put("DISTANCE",distance.getDistance());
            List<Map<String, Object>> dictList = dailyInspectService.getDictList();
            checkInfo.put("abnormalReasonType", dictList);
            return ResultEntity.success(checkInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }



    /**
     * 获取日检查的检查项目列表
     * @param checkId 检查ID
     * @return
     */
    @GetMapping("checkItemList")
    public ResultEntity<Map<String,Object>> checkItemList(Long checkId,Long companyId){
        try {
            Map<String,Object> result  = new HashMap<>();
            List<Map<String,Object>> itemList = doubleRandomCheckService.selectCheckItemList(checkId,companyId);
            result.put("templateName",itemList.size() > 0 ? itemList.get(0).get("TEMPLATE_NAME") : "");
            result.put("itemList",itemList);
            return ResultEntity.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 保存检查项结果内容
     * @param checkId 检查Id
     * @param standardId 检查标准id
     * @param contentId 检查内容Id
     * @param result 选择的结果 1是、2否、3合理缺项
     * @param problemContent 问题描述选择的内容
     * @param checkExplain 检查说明选择的内容
     * @param problemContentInput 问题描述输入的内容
     * @param missingItemContentInput 检查说明输入的内容
     * @return
     */
    @PostMapping("saveCheckItem")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity saveCheckItem(Long checkId,Long standardId,Long contentId,String result,
                                      String problemContent,String checkExplain,String problemContentInput,String missingItemContentInput
    ){
        try {
            doubleRandomCheckService.saveCheckItem( checkId,  standardId, contentId, result,
                    problemContent, checkExplain,problemContentInput, missingItemContentInput);
            return ResultEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("上传失败");
        }
    }

    /**
     * 保存检查门头照照片
     * @param checkId 检查Id
     * @param file 门头照文件
     * @return
     */
    @PostMapping("uploadCheckFile")
    public ResultEntity uploadCheckFile(Long checkId, MultipartFile file){
        try {
            JgDailyCheck check =  doubleRandomCheckService.uploadCheckFile( checkId, file);
            return ResultEntity.success(check);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("操作失败");
        }
    }


    /**
     * 上传检查项的问题照片
     * @param checkId 检查Id
     * @param contentId 检查内容Id
     * @param file
     * @return
     */
    @PostMapping("uploadItemFile")
    public ResultEntity uploadItemFile(Long checkId, Long standardId,Long contentId,MultipartFile file
    ){
        try {
            String fileUrl = doubleRandomCheckService.uploadItemFile( checkId, standardId, contentId, file);
            return ResultEntity.success(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("操作失败");
        }
    }



    /**
     * 保存/临时保存检查项结果内容
     * @param checkId 检查id
     * @param manageStatus 经营状态：0正常，1异常
     * @param abnormalCause 异常原因
     * @param auditTrails  异常核查记录
     * @param rectifyTime  异常整改时间
     * @param checkResults  异常检查结果
     * @param exprocessResults  异常处理结果
     * @param companyPic  门头照(file标签的文件二进制流)
     * @param processResults  检查处理结果：1通过检查，2责令整改，3调查处理
     * @param otherProblem  其他问题
     * @param temporary  是否临时1-是；2-否
     * @param rectificationTimeLimit 整改时限
     * @param rectificationSituationData 页面中选择的内容json
     * @return
     */
    @PostMapping("saveCheckInfo")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity saveCheckInfo(Long checkId, String manageStatus,
                                      String abnormalCause,String auditTrails,String rectifyTime,String checkResults,String exprocessResults,
                                      @RequestPart(required = false,name = "companyPic") MultipartFile companyPic,
                                      String processResults,String otherProblem,String temporary,String rectificationTimeLimit, String rectificationSituationData,String contactPhone
    ){
        try {
            RectificationSituationData rectificationSituationDataObject = JSONObject.parseObject(rectificationSituationData, RectificationSituationData.class);
            JgDailyCheck dailyCheck =  doubleRandomCheckService.saveCheckInfo(checkId, manageStatus,
                    abnormalCause,auditTrails,rectifyTime,checkResults,exprocessResults, companyPic,
                    processResults,otherProblem,temporary,rectificationTimeLimit,rectificationSituationDataObject,contactPhone);
            return ResultEntity.success(dailyCheck);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("保存/临时保存检查项结果内容失败");
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 最终保存
     * @param checkId
     * @return
     */
    @PostMapping("finaSaveInfo")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity finaSaveInfo(Long checkId,String processResults,String rectificationTimeLimit,String contactPhone){
        try {
            JgDailyCheck dailyCheck =  doubleRandomCheckService.finaSaveInfo(checkId,processResults,rectificationTimeLimit,contactPhone );
            return ResultEntity.success(dailyCheck);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("保存/临时保存检查项结果内容失败");
            return ResultEntity.error("操作失败");
        }
    }


    /**
     * 上传结果记录的文件
     * @param checkId 日常检查结果表id
     * @param imgFile 二进制文件流
     * @param type 1-要点表；2-记录表
     * @return
     */
    @PostMapping("uploadResultRecord")
    public ResultEntity uploadResultRecord(Long checkId,@RequestPart(required = true,name = "imgFile") MultipartFile imgFile,String type
    ){
        try {
            if (imgFile != null && StringUtils.isBlank(imgFile.getOriginalFilename())) {
                return ResultEntity.error("请上传文件");
            }
            doubleRandomCheckService.uploadResultRecord(checkId,imgFile,type);
            return ResultEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传结果记录的文件失败");
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 保存告知单
     * @param checkAddress 检查地址
     * @param checkPerson1Id 第一检查人id
     * @param checkPerson1SignFile 第一检查人签名文件流
     * @param checkPerson2Id 第二检查人id
     * @param checkPerson2SignFile 第二检查人签名文件流
     * @param checkId 检查Id
     * @param companySignFile 企业签名文件流
     * @param isAvoid  是否回避0-否；1-是
     * @param notifyMatters
     * @return
     */
    @PostMapping("saveCheckInform")
    public ResultEntity saveCheckInform(Long checkId,Long checkPerson1Id,Long checkPerson2Id,
                                        String checkAddress,String notifyMatters,String isAvoid,String  companySignFile
            ,String  checkPerson1SignFile
            ,String  checkPerson2SignFile
            ,String  informFile
    ){
        try {
            String urlPath  = doubleRandomCheckService.saveCheckInform(checkId,  checkPerson1Id, checkPerson2Id,
                    checkAddress, notifyMatters, isAvoid,  companySignFile, checkPerson1SignFile, checkPerson2SignFile,informFile);
            return ResultEntity.success(urlPath);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询检查内容的列表失败");
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 查询检查完成的订单
     * @param checkId 日常检查表id
     * @return
     */
    @GetMapping("getCheckResultInfo")
    public ResultEntity getCheckResultInfo(Long checkId){
        try {
            Map<String, Object> result = doubleRandomCheckService.getCheckResultInfo(checkId);
            return ResultEntity.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询检查完成的订单失败");
            return ResultEntity.error("操作失败");
        }
    }

}
